import Data.List
import System.IO
import System.Environment

main = do    

    let c = takeAll "2 - 4 * 2 + 8 / 2" 
    print c
    

    print "--------------------------------------"

getOpPriority ::(Num a) => String-> a
getOpPriority x
    | x `elem` ["+","-"] = 1 
    | x `elem` [ "*", "/"] = 2 

getOpPriority2 ::(Num a) => String-> a
getOpPriority2 "+" = 1
getOpPriority2 "-" = 1
getOpPriority2 "*" = 2
getOpPriority2 "/" = 2



calStr::(RealFloat a)=> a->a->String->a
calStr x y "+" = x + y
calStr x y "-" = x - y
calStr x y "*" = x * y
calStr x y "/" = x / y
calStr x y  op = x


takeAll ::(RealFloat a, Read a) => String-> a
takeAll str = take5 aaa bbb
    where   (aa, bb) = take4 ([], []) (words str)
            aaa = reverse aa
            bbb = reverse bb


take5 ::(RealFloat a) => [a]->[String]-> a
take5 (x:y:xs) (op1:ops) = take5 ((calStr x y  op1):xs) ops
take5 (x:xs) ops = x

take4a ::(RealFloat a, Read a) => ([a], [String])->[String]->([a], [String])
take4a (digits, operators) [] = (digits, operators)
take4a (digit1:digits, op1:operators) (x:x2:xs)
    | (x `elem` ["+","-", "*", "/"]) && ( getOpPriority2 x >  getOpPriority2 op1 )= 
    take4a (calStr digit1 (read x2) x : digits,  op1:operators)  (xs)            
take4a (digits, operators) (x:xs)
    | x `elem` ["+","-", "*", "/"] = take4 (digits,  (x:operators))  xs
    | otherwise =  take4a ( read x : digits, operators)  xs
    
take4 ::(RealFloat a, Read a) => ([a], [String])->[String]->([a], [String])
take4 (digits, operators) [] = (digits, operators)
take4 (digit1:digits, op1:operators) (x:x2:xs)
    | x `elem` ["+","-", "*", "/"] = 
        if getOpPriority2 x >  getOpPriority2 op1 
            then  take4 (calStr digit1 (read x2) x : digits,  op1:operators)  (xs)
            else  take4 ( digit1:digits,  x:op1:operators)  (x2:xs)
    | otherwise =  take4 ( read x : digit1:digits, op1:operators)  (x2:xs)
take4 (digits, operators) (x:xs)
    | x `elem` ["+","-", "*", "/"] = take4 (digits,  (x:operators))  xs
    | otherwise =  take4 ( read x : digits, operators)  xs



